#include <task.h>
#include "task_desc.h"
#include "task_list.h"

/*************************
 * Tasks list management *
 *************************/

/* The tasks list is a doubly linked circular list.
 * The double linkage ease the removal of tasks.
 *
 * Also, when a task is removed, it preserve its links,
 * so that it still knows its next tasks, and the
 * scheduling can properly continue.
 */

task_t task_list_head = NULL;

/* Add the task 't' to the task list */
void task_list_add (task_t t) {
  if (task_list_head == NULL) {
    task_list_head = t->next = t->prev = t;
  } else {
    task_list_head->prev->next = t;
    t->prev = task_list_head->prev;
    t->next = task_list_head;
    task_list_head->prev = t;
  }
}

/* Remove the task 't' from the task list */
void task_list_remove (task_t t) {
  if (t->next == t) {
    t->prev = t->next = NULL;
  } else {
    t->prev->next = t->next;
    t->next->prev = t->prev;
  }

  if (task_list_head == t)
    task_list_head = t->next;
}

/* Return the next task or NULL if the list is empty */
task_t task_list_next (task_t t) {
  return t->next;
}
